package com.nondo.rdp.finance.endpoint.wap.app;

import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.event.PointApplicationEvent;
import com.nondo.rdp.auth.listener.PointApplicationListener;
import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.core.service.RulesService;
import com.nondo.rdp.finance.domain.Article;
import com.nondo.rdp.finance.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller("apiWapInvite")
@RequestMapping("/wap/app/invite")
public class InviteEndpoint {
    @Autowired
    ArticleService articleService;

    @Autowired
    RulesService rulesService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    UserService userService;

    /**
     * 获取邀请信息
     * @param request
     * @param response
     * @param uid
     * @return
     */
    @RequestMapping("/info")
    public ModelAndView list(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "uid", required = false) Long uid) {
        ModelAndView mv = new ModelAndView("wap/app/invite/info");

        Map map = new HashMap();
        //获取类型为invite的文章
        Article article = this.articleService.findByType("invite");
        if (article != null) {
            map.put("title", article.getTitle());
            map.put("body", article.getBody());

            //增加分享者的积分
            if (uid != null) {
                User user = this.userService.findOne(uid);
                if (user != null) {
                    //调用积分事件
                    applicationEventPublisher.publishEvent(new PointApplicationEvent(this, user, PointApplicationListener.TYPE_INVITE_SHARE_VIEW));
                }
            }
        } else {
            map.put("title", "内容未找到");
            map.put("body", "内容跑到火星去了,我们正在极力找回");
        }

        mv.addObject("article", article);

        return mv;
    }
}